package com.jfsnpm.common;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class MenuTree {
	public String tsid;
	public String tspid;
	public String tstext;
	public String tsurl;
	public String tssortno;
	public String tssystem;
	public List<MenuTree> children;
	public boolean newnode=false;
	
	/**
	 * 保存树	
	 * 			1.自动判断是否为新增节点	newnode		boolean
	 * 				若为新增节点，生成UUID。
	 * 			2.自动更新父序号			tspid		String
	 * 			3.自动更新排序号			tssortno	String
	 * 			4.更新到数据库表 pm_menu[id,pid,url,text,sortno,status]	
	 * @return this
	 */
	public boolean saveTree(){
		Record tree;
		if(StringUtils.isBlank(tsid)){
			newnode = true;
			tsid = AppTool.getUUID();
		}
		if(newnode){
			tree = new Record().set("id", tsid);
		}else{
			tree = Db.findById("pm_menu", tsid);
		}
		tree.set("pid", tspid).set("url", tsurl).set("text", tstext).set("sortno", tssortno).set("system", tssystem);
		if(children != null&&children.size()>0){
			for(int  i = 0   ; i < children.size(); i++) {
				children.get(i).tspid = tsid;
				children.get(i).tssortno = String.valueOf(i);
				if(!children.get(i).saveTree()) return false;
			}
		}
		if(newnode){
			if(Db.save("pm_menu", tree)) return true;
		}else{
			if(Db.update("pm_menu", tree)) return true;
		}
		return false;
	}
	
	
	
}
